<template>
    <!-- 最上面卡片 -->
    <div class="detal-box">
        <TopCard @tabChange="tabChange" />
        <div v-show="activeIndex == 1">
            <!-- 基本信息 -->
            <BasicForm ref="basic" @getVariable="hqVariable" />
            <!-- 配置信息 -->
            <ConfigureForm v-if="isEdit === '2'" ref="gure" :appAccess="appAccess" />
            <AnnexForm v-if="isEdit === '2'" ref="annex" />
        </div>
        <ProcessHistory v-show="activeIndex == 2" :datas="historyAudit" />
        <FlowChart v-show="activeIndex == 3" :datas="chartData" />
        <!-- 按钮 -->
        <!-- <div class="uiue-card btn" :class="{ btnposi: activeIndex == 2 || activeIndex == 3 }"> -->
        <div class="btnBottom" :class="{ btnposi: activeIndex == 2 || activeIndex == 3 }">
            <a-button class="bt1" :loading="btnloding" @click="backs">取消</a-button>
            <a-button type="primary" :loading="btnloding" @click="submit"> 提交{{ type === '1' ? '' : '审批'
                }}</a-button>
        </div>
        <!-- </div> -->
    </div>
    <PickPeoplea ref="pick" @succses="setUser" @cancel="handCancel" :setPersions="true"
        v-if="roleList.length > 0 && flowId === 'app_new_create'" :roleList="roleList" />
    <PickPeople ref="pick" @succses="setUser" @cancel="handCancel" :setPersions="true"
        v-if="roleList.length > 0 && flowId !== 'app_new_create'" :roleList="roleList" />
</template>

<script setup name="TestForm">
import appInfoApi from '@/api/biz/appInfoApi'
import approvalApi from '@/api/biz/approvalApi'
import bizRoleApi from '@/api/biz/bizRoleApi'
import ProcessHistory from '@/components/ProcessHistory/index.vue'
import FlowChart from '@/components/FlowChart/index.vue'
import PickPeople from '@/components/pickPeople/index.vue'
import PickPeoplea from '@/components/pickPeople/indexa.vue'
import { cloneDeep } from 'lodash-es'
import BasicForm from './basicForm.vue'
import ConfigureForm from './configure/index.vue'
import AnnexForm from './annexForm.vue'
import TopCard from './topCard.vue'
import sysConfig from '@/config/index'
import { useRoute, useRouter } from "vue-router";
import { message, Modal } from 'ant-design-vue'
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import store from '@/store'
const route = useRoute()
const router = useRouter()
const formData = ref({})
const formAccount = ref({ testAccount: '' })
const formRules = {
    testAccount: [{ required: true, message: '请输入测试账号', trigger: 'blur' }],
}
// 双端接入
const appAccess = ref([])
const basic = ref(null)
const gure = ref(null)
const annex = ref(null)
const pick = ref(null)
const acco = ref(null)
const btnloding = ref(false)
let isPcTodo = ref('1')
let isPcReadtodo = ref('1')
// isEdit是否是编辑 --- 1否  2是
const { isEdit } = route.query
const activeIndex = ref('1')
const historyAudit = ref([])
// const detailDate = ref()
onMounted(() => {
    // if (type === '1') {
    //     formData.value = {}
    // }
    // if (type === '2') {
    //     getDate()
    //     getChart()
    //     if (messageTrackId) {
    //         getAudit()
    //     }
    // }
})
//路由返回
const backs = () => {
    store.commit('removeViewTags', route)
    router.back()
}
const getAudit = async () => {
    historyAudit.value = await approvalApi.getAudit({ id: messageTrackId })
}
const getDate = async () => {
    let datas = messageTrackId ? await appInfoApi.appInfowaitDetails({ messageTrackId }) : await appInfoApi.getdetailByappId({ appId })
    if (messageTrackId) {
        if (datas.appAccess.includes('1')) {
            datas.appInfoPcPropertiesAddParam = datas.pcPropertiesList[0]
        }
        if (datas.appAccess.includes('1')) {
            datas.appInfoAppPropertiesAddParam = datas.appPropertiesList[0]
        }
    }
    // if (revise) {
    //     // 如果是变更
    //     obj = await appInfoApi.getdetailByappId({ appId })
    // }
    appAccess.value = datas.appAccess ? datas.appAccess.split(',') : []
    isPcTodo.value = datas.isPcTodo ? datas.isPcTodo : '1'
    isPcReadtodo.value = datas.isPcReadtodo ? datas.isPcReadtodo : '1'
    formAccount.value.testAccount = datas.testAccount
    // 详情信息供子组件展示使用
    store.dispatch('setDetail', datas)
}
const chartData = ref()
const getChart = async () => {
    const id = 'test_create_or_upgrade'
    chartData.value = await approvalApi.getFlowchartByFlow({ id })
}

// tab切换事件
const tabChange = (index) => {
    activeIndex.value = index
}

const fiterForm = () => {
    const obj = cloneDeep(formData.value)
    const tableName = route.query.tableName
    obj.appAccess = obj.appAccess.join(',')
    obj.networkConnFile = JSON.stringify(obj.networkConnFile)
    if (tableName) {
        if (tableName.includes('PC')) {
            obj.appInfoPcPropertiesAddParam.compatibility = obj.appInfoPcPropertiesAddParam.compatibility.join(',')
        }
    } else {
        if (obj.appAccess.includes('1')) {
            obj.appInfoPcPropertiesAddParam.compatibility = obj.appInfoPcPropertiesAddParam.compatibility.join(',')
        }
    }

    return obj
}


// 是否接入pc待办
provide('isPcTodo', isPcTodo)
// 是否接入pc待阅
provide('isPcReadtodo', isPcReadtodo)
// 根据type给不同的变量赋值
const hqVariable = (e, type) => {
    if (type === 'appAccess') appAccess.value = e
    if (type === 'isPcTodo') isPcTodo.value = e
    if (type === 'isPcReadtodo') isPcReadtodo.value = e
}

const lastClickTime = ref(0)
const clickInterval = ref(1000) // 定义点击间隔为1秒
// 效验表单
const submit = async () => {
    const currentTime = Date.now();
    if (currentTime - lastClickTime.value < clickInterval.value) {
        // 时间间隔过小，直接返回
        return;
    }
    lastClickTime.value = currentTime;


    // const config = sysConfig.DEVICE_CONFIG
    // 调用子组件basic的校验方法并返回子组件的formData
    const basicVali = await basic.value.handleValidate()
    if (basicVali) {
        formData.value = cloneDeep(basicVali)
    } else {
        message.warning('请完善基本信息')
        return false
    }
    // let verify = ''
    // if (revise || messageTrackId) {
    //     // 告诉后台修改的是什么类型的应用
    //     verify = route.query.tableName
    //     let str = config.find((v) => route.query.tableName.includes(v.oid)).key
    //     formData.value.editAppType = str

    // } else {
    //     if (appAccess.value.length > 1) {
    //         // 多端
    //         verify = 'PC,APP'
    //     } else {
    //         // 单端
    //         verify = appAccess.value[0] == 1 ? 'PC' : 'APP'
    //     }
    // }
    // if (formTypeId) {
    //     // 变更
    //     verify = route.query.tableName
    //     // 告诉后台修改的是什么类型的应用
    //     let str = config.find((v) => route.query.tableName.includes(v.oid)).key
    //     formData.value.editAppType = str
    // } else {
    //     // 新增和被退回到审批人的工单
    //     if (appAccess.value.length > 1) {
    //         // 多端
    //         verify = 'PC,APP'
    //     } else {
    //         // 单端
    //         verify = appAccess.value[0] == 1 ? 'PC' : 'APP'
    //     }
    // }


    // // 调用孙子组件portalForm的校验方法
    // if (appAccess.value.includes('1') && verify.includes('PC')) {
    //     const portal = await gure.value.portalValidate()
    //     if (portal) {
    //         formData.value.appInfoPcPropertiesAddParam = cloneDeep(portal)
    //     } else {
    //         message.warning('请完善门户端HTML配置信息')
    //         return false
    //     }
    // }
    // // 调用孙子组件mobileForm的校验方法
    // if (appAccess.value.includes('2') && verify.includes('APP')) {
    //     const mobile = await gure.value.mobileValidate()
    //     if (mobile) {
    //         formData.value.appInfoAppPropertiesAddParam = cloneDeep(mobile)
    //         setParam()
    //     } else {
    //         message.warning('请完善移动端HTML配置信息')
    //         return false
    //     }
    // }
    // 调用子组件annex的校验方法并返回子组件的formData
    // const annexVali = await annex.value.handleValidate()
    // if (annexVali) {
    //     formData.value = { ...formData.value, ...annexVali }
    // } else {
    //     message.warning('请完善附件信息')
    //     return false
    // }
    onOK()
    // 数据格式化并提交
}
const flowId = ref('')
const onOK = async () => {

    // 数据处理
    // let obj = fiterForm()
    // if (type === '1') {
    const obj = cloneDeep(formData.value)
    const flowParams = {
        isPcTodo: obj.isPcTodo,
        isPcReadtodo: obj.isPcReadtodo,
        isAppTodo: obj.isAppTodo,
        isAppReadtodo: obj.isAppReadtodo,
        appRange: obj.appRange,
        type: '0'    // 0 新建应用 4 接入
    }
    obj.appAccess = obj.appAccess.join(',')
    if (isEdit === '1') {
        // 根据表单项获取流程id
        const res = await appInfoApi.getFlowNew(flowParams)
        flowId.value = res.flow;
        // 用流程id获取人员列表
        getRoleList({ appAccess: obj.appAccess, flow: res.flow })
    }



    // if (isEdit === '1') {
    //     btnloding.value = true
    //     appInfoApi.addTest(obj).then(res => {
    //         btnloding.value = false
    //         backs()
    //     }).catch(err => {
    //         btnloding.value = false
    //     })
    // }





    // }
    // if (type === '2') {
    //     let obj11 = {
    //         appAccess: obj.appAccess
    //     }
    //     getRoleList(obj11)
    // }
}
// 给h5参数信息赋值
const setParam = () => {
    const obj1 = {}
    let arr = []
    obj1[formData.value.appName] = {
        appid: 'xxxxx',
        appname: formData.value.appName,
        id: 'xxxxx',
        params: {
            app_name: '',
            app_type: '', // db || yb || dy || yy
            tag_type: '',
            encode_url: '',
            title: '',
            url: ''
        },
        subsystem: '其他',
        system: formData.value.appName,
        tagtype: '其他'
    }

    if (formData.value.isAppTodo === '1') {
        // 接入待办
        let appType = ['db', 'yb']
        appType.forEach((v) => {
            let obj = cloneDeep(obj1)
            obj[formData.value.appName].params.app_type = v
            arr.push(obj)
        })
    }
    if (formData.value.isAppReadtodo === '1') {
        // 接入待阅
        let appType = ['dy', 'yy']
        appType.forEach((v) => {
            let obj = cloneDeep(obj1)
            obj[formData.value.appName].params.app_type = v
            arr.push(obj)
        })
    }

    formData.value.appInfoAppPropertiesAddParam.param = arr.length > 0 ? JSON.stringify({ ...arr }) : ''
}
// 提交审批
const submitFlow = () => {
    approvalApi.submitTask({ approvalUsers: formData.value.approvalUsers, id: messageTrackId, yesOrNo: 'Y', auditAgree: '同意' })
        .then(() => {
            btnloding.value = false
            backs()
        })
        .catch((err) => {
            btnloding.value = false
        })
}
const lastOk = () => {
    btnloding.value = true
    // 数据处理
    // let obj = fiterForm()
    const obj = cloneDeep(formData.value)
    obj.appAccess = obj.appAccess.join(',')
    // 去掉所有值的前后空格
    const trimmedValues = Object.fromEntries(
        Object.entries(obj).map(([key, value]) => [key, value ? typeof value === 'string' ? value.trim() : value : value])
    );
    appInfoApi.createInfo({ ...trimmedValues }).then(() => {
        btnloding.value = false
        backs()
    }).catch(err => {
        btnloding.value = false
    })

    // if (messageTrackId) {
    //     // 被退回再提交
    //     appInfoApi.backEdit({ ...obj, ...formAccount.value })
    //         .then(() => {
    //             submitFlow()
    //         })
    // } else if (revise) {
    //     // 编辑
    //     appInfoApi.testFlowEdit({ ...obj, ...formAccount.value }).then(() => {
    //         btnloding.value = false
    //         backs()
    //     }).catch(err => {
    //         btnloding.value = false
    //     })
    // } else {
    //     appInfoApi.testFlowAdd({ ...obj, ...formAccount.value }).then(() => {
    //         btnloding.value = false
    //         backs()
    //     }).catch(err => {
    //         btnloding.value = false
    //     })
    // }

}

const handCancel = () => {
    roleList.value = []
}

// 获取选人组件的角色
let roleList = ref([])
const getRoleList = async (params) => {
    const obj = {
        roleId: params.flow,
        searchKey: params.appAccess,
        ascriptionId: formData.value.platformBelongId,
        appRange: formData.value.appRange,
    }
    roleList.value = await bizRoleApi.getList(obj)
    if (roleList.value.length == 0) {
        Modal.confirm({
            title: '提示',
            icon: createVNode(ExclamationCircleOutlined),
            content: '当前环节无可选人员，请联系双门户管理员hqs-swxreq@chinaunicom.cn',
            okText: '确认',
            cancelText: '取消',
        });
    }

    if (pick.value) {
        pick.value.setVisible(true)
    }
}
// 人员选择完成
const setUser = (user) => {
    if (user && user.length > 0) {
        formData.value.approvalUsers = user
        pick.value.setVisible(false)
        lastOk()
    }
}
</script>

<style lang="less" scoped>
.btn {
    text-align: right;

    .bt1 {
        margin-right: 10px;
    }
}

.btnposi {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
}

.form-box {
    margin-top: 14px;
    padding-bottom: 30px;

    &-inp {
        border-radius: 4px;
        border: 1px solid rgb(206, 206, 206);
    }
}
</style>





<!-- <style lang="less" scoped>
.btn {
    text-align: right;

    .bt1 {
        margin-right: 10px;
    }
}

.btnBottom {
    display: flex;
    justify-content: end;

    .bt1 {
        margin-right: 10px;
    }
}

.btnposi {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 100%;
}
</style> -->